package com.ynwt.thread;

import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.ynwt.model.ycoin.YcoinRankItem;
import com.ynwt.model.ycoin.YcoinRankResponse;
import com.ynwt.repository.UserDao;
import com.ynwt.service.RankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by huangying on 2017/5/31.
 */
@Component
public class WeekYcoinRankThread implements Runnable {

    private String openid;

    public WeekYcoinRankThread setOpenid(String openid) {
        this.openid = openid;
        return this;
    }

    @Override
    public void run() {
        YcoinRankResponse ycoinRankResponse = rankService.weekYcoinRank(openid, 0L, 110L);

        StringBuffer sb = new StringBuffer();

        //设置新增逸贝数
        sb.append("您本周共新增【")
                .append(ycoinRankResponse.getUserRank().getYcoin())
                .append("】个逸贝，每周从周一起新增的逸贝数就是您的周新增逸贝数哦～\n\n");

        //设置头部内容
        sb.append("【周逸贝排行榜】\n名次：逸贝数-->昵称\n================\n")
                .append("第").append(ycoinRankResponse.getUserRank().getPlace()).append("名：")
                .append(ycoinRankResponse.getUserRank().getYcoin()).append("-->")
                .append(userDao.findByUnionid(ycoinRankResponse.getUserRank().getUnionid()).getNickname())
                .append("\n---------------\n");

        List<YcoinRankItem> list = ycoinRankResponse.getRankItems();

        //判断是否需要发两条消息
        int numOne;
        int numTwo = 0;
        if (list.size() < 50) {
            numOne = list.size();
        } else {
            numOne = 50;
            numTwo = list.size();
        }

        //发送第一条消息
        for (int i = 0; i < numOne; i++) {
            sb.append("第").append(list.get(i).getPlace()).append("名：")
                    .append(list.get(i).getYcoin()).append("-->")
                    .append(list.get(i).getNickname()).append("\n");
        }
        customAPI.sendCustomMessage(openid, new TextMsg(sb.toString()));

        //发送第二条消息
        if (numTwo > 0) {
            sb.setLength(0);
            for (int i = numOne; i < numTwo; i++) {
                sb.append("第").append(list.get(i).getPlace()).append("名：")
                        .append(list.get(i).getYcoin()).append("-->")
                        .append(list.get(i).getNickname()).append("\n");
            }
            customAPI.sendCustomMessage(openid, new TextMsg(sb.toString()));
        }
    }

    @Autowired
    private RankService rankService;

    @Autowired
    private CustomAPI customAPI;

    @Autowired
    private UserDao userDao;
}
